﻿using System;
using System.Collections.Generic;
using System.Web.Mail;
using System.Net.Mail;
using System.Linq;
using System.Text;
using TDS.IO;
namespace TDS.Mail
{
    public class MailManager
    {
        public MailManager()
        {

        }

        /// <summary>
        /// System.Web.Mail.MailMessage' is obsolete: 'The recommended alternative is System.Net.Mail.MailMessage. http://go.microsoft.com/fwlink/?linkid=14202'
        /// </summary>
        /// <param name="sHost"></param>
        /// <param name="nPort"></param>
        /// <param name="sUserName"></param>
        /// <param name="sPassword"></param>
        /// <param name="sFromName"></param>
        /// <param name="sFromEmail"></param>
        /// <param name="sToName"></param>
        /// <param name="sToEmail"></param>
        /// <param name="sToCCEmail"></param>
        /// <param name="sToBCCEmail"></param>
        /// <param name="sHeader"></param>
        /// <param name="sMessage"></param>
        /// <param name="fSSL"></param>
        /// <returns></returns>
        public static bool SendWebMail(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
        string sToName, string sToEmail, string sToCCEmail, string sToBCCEmail, string sHeader, string sMessage, bool fSSL)
        {
            try
            {
                System.Web.Mail.MailMessage _mailMessage = new System.Web.Mail.MailMessage();

                _mailMessage = CreateWebMailMessage(sHost, nPort, sUserName, sPassword, sFromName, sFromEmail,
                                sToName, sToEmail, sToCCEmail, sToBCCEmail, sHeader, sMessage, fSSL);

                System.Web.Mail.SmtpMail.SmtpServer = sHost;
                System.Web.Mail.SmtpMail.Send(_mailMessage);
            }
            catch (Exception Ex)
            {
                string _emailSetting = "Host : " + sHost + " From Email : " + sUserName + " To Email : " + sToEmail + " Subject : " + sHeader;
                CreateExceptionLog(Ex, _emailSetting, "SendMail Exception");
                return false;
            }
            return true;
        }

        private static System.Web.Mail.MailMessage CreateWebMailMessage(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
        string sToName, string sToEmail, string sToCCEmail, string sToBCCEmail, string sHeader, string sMessage, bool fSSL)
        {
            if (sToName.Length == 0)
                sToName = sToEmail;
            if (sFromName.Length == 0)
                sFromName = sFromEmail;

            System.Web.Mail.MailMessage _mailMessage = new System.Web.Mail.MailMessage();
            _mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = sHost;
            _mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;

            _mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = nPort.ToString();
            if (fSSL)
                _mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true";

            if (sUserName.Length == 0)
            {
                //Ingen auth 
            }
            else
            {
                _mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
                _mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = sUserName;
                _mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = sPassword;
            }

            _mailMessage.To = sToEmail;
            _mailMessage.From = sFromEmail;
            _mailMessage.Subject = sHeader;
            _mailMessage.Body = sMessage;
            _mailMessage.Cc = sToCCEmail;
            _mailMessage.Bcc = sToBCCEmail;

            _mailMessage.BodyFormat = System.Web.Mail.MailFormat.Html;
            System.Web.Mail.SmtpMail.SmtpServer = sHost;

            return _mailMessage;
        }

        public static bool SendWebMailByAttachments(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
        string sToName, string sToEmail, string sToCCEmail, string sToBCCEmail, string sHeader, string sMessage, bool fSSL, string[] fileList)
        {
            bool _retValue = false;
            try
            {

                System.Web.Mail.MailMessage _mailMessage = new System.Web.Mail.MailMessage();

                _mailMessage = CreateWebMailMessage(sHost, nPort, sUserName, sPassword, sFromName, sFromEmail,
                                sToName, sToEmail, sToCCEmail, sToBCCEmail, sHeader, sMessage, fSSL);

                for (int i = 0; i < fileList.Length; i++)
                {
                    _mailMessage.Attachments.Add(new System.Web.Mail.MailAttachment(fileList[i].ToString()));
                }

                System.Web.Mail.SmtpMail.Send(_mailMessage);
                _retValue = true;
            }
            catch (Exception Ex)
            {
                string _emailSetting = "Host : " + sHost + " From Email : " + sUserName + " To Email : " + sToEmail + " Subject : " + sHeader;
                CreateExceptionLog(Ex, _emailSetting, "SendMailByAttachments Exception");
                _retValue = false;
            }

            return _retValue;
        }

        public static System.Net.Mail.MailMessage CreateNetMailMessage(string sFromName, string sFromEmail,
        string sToName, string sToEmail, string sCCEmail, string sBCCEmail, string sHeader, string sMessage)
        {
            if (sToName.Length == 0)
                sToName = sToEmail;
            if (sFromName.Length == 0)
                sFromName = sFromEmail;

            System.Net.Mail.MailMessage _mailMessage = new System.Net.Mail.MailMessage();

            if (sToEmail != "")
            {
                string[] sGetToEmails = sToEmail.Split(';');

                foreach (string toemail in sGetToEmails)
                {
                    if (toemail != "")
                        _mailMessage.To.Add(new MailAddress(toemail, sToName));
                }
            }

            if (sCCEmail != "")
            {
                string[] sGetCCEmails = sCCEmail.Split(';');

                foreach (string ccemail in sGetCCEmails)
                {
                    if (ccemail != "")
                        _mailMessage.CC.Add(new MailAddress(ccemail));
                }
            }

            if (sBCCEmail != "")
            {
                string[] sGetBCCEmails = sBCCEmail.Split(';');

                foreach (string bccemail in sGetBCCEmails)
                {
                    if (bccemail != "")
                        _mailMessage.Bcc.Add(new MailAddress(bccemail));
                }

            }

            MailAddress _fromMail = new MailAddress(sFromEmail, sFromName);

            _mailMessage.From = _fromMail;

            _mailMessage.Subject = sHeader;
            _mailMessage.Body = sMessage;
            _mailMessage.IsBodyHtml = true;
            _mailMessage.ReplyTo = new MailAddress(sFromEmail);
            return _mailMessage;
        }

        public static bool SendNetMail(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
        string sToName, string sToEmail, string sCCEmail, string sBCCEmail, string sHeader, string sMessage, bool fSSL)
        {
            try
            {
                System.Net.Mail.MailMessage _mailMessage = new System.Net.Mail.MailMessage();

                _mailMessage = CreateNetMailMessage(sFromName, sFromEmail,
                                sToName, sToEmail, sCCEmail, sBCCEmail, sHeader, sMessage);

                SmtpClient smtp = new SmtpClient();
                smtp.Port = nPort;
                smtp.Host = sHost;
                smtp.Credentials = new System.Net.NetworkCredential(sUserName, sPassword);

                if (fSSL)
                {
                    smtp.EnableSsl = true;
                }

                smtp.Send(_mailMessage);
            }
            catch (Exception Ex)
            {
                string _emailSetting = "Host : " + sHost + " From Email : " + sUserName + " To Email : " + sToEmail + " Subject : " + sHeader;
                CreateExceptionLog(Ex, _emailSetting, "SendNetMail Exception");

                return false;
            }

            return true;
        }

        public static bool SendNetMailByAttachements(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
string sToName, string sToEmail, string sCCEmail, string sBCCEmail, string sHeader, string sMessage, bool fSSL, string[] fileList)
        {
            try
            {
                System.Net.Mail.MailMessage _mailMessage = new System.Net.Mail.MailMessage();

                _mailMessage = CreateNetMailMessage(sFromName, sFromEmail,
                                sToName, sToEmail, sCCEmail, sBCCEmail, sHeader, sMessage);

                for (int i = 0; i < fileList.Length; i++)
                {
                    if (fileList[i] != null)
                    {
                        Attachment _aAttachment = new Attachment(fileList[i].ToString());
                        _mailMessage.Attachments.Add(_aAttachment);
                    }
                }

                SmtpClient smtp = new SmtpClient();
                smtp.Port = nPort;
                smtp.Host = sHost;
                smtp.Credentials = new System.Net.NetworkCredential(sUserName, sPassword);

                if (fSSL)
                {
                    smtp.EnableSsl = true;
                }

                smtp.Send(_mailMessage);
            }
            catch (Exception Ex)
            {
                string _emailSetting = "Host : " + sHost + " From Email : " + sUserName + " To Email : " + sToEmail + " Subject : " + sHeader;
                CreateExceptionLog(Ex, _emailSetting, "SendNetMail Exception");

                return false;
            }

            return true;
        }

        public static bool SendNetMailAsync(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
        string sToName, string sToEmail, string sCCEmail, string sBCCEmail, string sHeader, string sMessage, bool fSSL)
        {
            try
            {
                System.Net.Mail.MailMessage _mailMessage = new System.Net.Mail.MailMessage();

                _mailMessage = CreateNetMailMessage(sFromName, sFromEmail,
                                sToName, sToEmail, sCCEmail, sBCCEmail, sHeader, sMessage);

                object userState = _mailMessage;

                SmtpClient smtp = new SmtpClient();
                smtp.Port = nPort;
                smtp.Host = sHost;
                smtp.Credentials = new System.Net.NetworkCredential(sUserName, sPassword);

                if (fSSL)
                {
                    smtp.EnableSsl = true;
                }

                smtp.SendCompleted += new SendCompletedEventHandler(MailDeliveryComplete);
                smtp.SendAsync(_mailMessage, userState);

            }
            catch (Exception Ex)
            {
                string _emailSetting = "Host : " + sHost + " From Email : " + sUserName + " To Email : " + sToEmail + " Subject : " + sHeader;
                CreateExceptionLog(Ex, _emailSetting, "SendNetMailAsync Exception");

                return false;
            }

            return true;
        }


        public static bool SendNetMailByAttachmentsAsync(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
        string sToName, string sToEmail, string sCCEmail, string sBCCEmail, string sHeader, string sMessage, bool fSSL, string[] fileList)
        {
            try
            {
                System.Net.Mail.MailMessage _mailMessage = new System.Net.Mail.MailMessage();

                _mailMessage = CreateNetMailMessage(sFromName, sFromEmail,
                                sToName, sToEmail, sCCEmail, sBCCEmail, sHeader, sMessage);

                for (int i = 0; i < fileList.Length; i++)
                {
                    Attachment _aAttachment = new Attachment(fileList[i].ToString());
                    _mailMessage.Attachments.Add(_aAttachment);
                }

                object userState = _mailMessage;

                SmtpClient smtp = new SmtpClient();
                smtp.Port = nPort;
                smtp.Host = sHost;
                smtp.Credentials = new System.Net.NetworkCredential(sUserName, sPassword);

                if (fSSL)
                {
                    smtp.EnableSsl = true;
                }

                smtp.SendCompleted += new SendCompletedEventHandler(MailDeliveryComplete);
                smtp.SendAsync(_mailMessage, userState);

            }
            catch (Exception Ex)
            {
                string _emailSetting = "Host : " + sHost + " From Email : " + sUserName + " To Email : " + sToEmail + " Subject : " + sHeader;
                CreateExceptionLog(Ex, _emailSetting, "SendNetMailByAttachmentsAsync Exception");

                return false;
            }

            return true;
        }


        static void MailDeliveryComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            //Console.WriteLine("Message \"{0}\".", e.UserState);

            if (e.Error != null)
            {
                try
                {
                    //Get the Original MailMessage object
                    System.Net.Mail.MailMessage mail = (System.Net.Mail.MailMessage)e.UserState;

                    //write out the subject
                    string subject = mail.Subject;

                    System.Text.StringBuilder errorMsg = new System.Text.StringBuilder();
                    errorMsg.Append(string.Format("An error occurred sending message [{0}]. {1}", e.UserState.ToString(), e.Error.Message));

                    if (e.Error.InnerException != null)
                        errorMsg.Append(Environment.NewLine + "Inner exception message: " + e.Error.InnerException.Message);

                    errorMsg.Append(Environment.NewLine + "Subject: " + subject);
                    errorMsg.Append(Environment.NewLine + "Sender: " + mail.Sender.Address.ToString());
                    errorMsg.Append(Environment.NewLine + "Sender Host: " + mail.Sender.Host.ToString());
                    errorMsg.Append(Environment.NewLine + "From : " + mail.From.Address.ToString());
                    errorMsg.Append(Environment.NewLine + "From Host : " + mail.From.Host.ToString());
                    string _toAddresses = "";
                    foreach (MailAddress _msgMail in mail.To)
                    {
                        _toAddresses += _msgMail.Address.ToString() + ";";
                    }
                    errorMsg.Append(Environment.NewLine + "To : " + _toAddresses);
                    CreateMailDeliveryExceptionLog("SendNetMailAsync MailDeliveryComplete Exception", errorMsg);
                }
                catch (Exception Ex)
                {
                    Ex = null;
                }
            }
            else if (e.Cancelled)
            {
                //Console.WriteLine("Sending of email cancelled.");
            }
            else
            {
                //Console.WriteLine("Message sent.");
            }
        }


        private static void CreateExceptionLog(Exception Ex, string EmailSettingInfo, string strLocation)
        {
            String[] _fileContent = new String[7];
            _fileContent[0] = "Email Setting : " + EmailSettingInfo;
            _fileContent[1] = "Source : " + Ex.Source;
            _fileContent[2] = "Date Time : " + DateTime.Now.ToString();
            _fileContent[3] = "Stack Trace :" + Ex.StackTrace.ToString();
            _fileContent[4] = "Target Site : " + Ex.TargetSite.ToString();
            _fileContent[5] = "Location : " + "MOC.Utilities.Mail.MailManager - " + strLocation;
            _fileContent[6] = "Message : " + Ex.Message;

            WriteExceptionLog("Mail_", _fileContent);
        }


        private static void WriteExceptionLog(string strPrefixFileName, string[] strException)
        {
            try
            {
                TDS.IO.FileSystem _newFile = new TDS.IO.FileSystem();
                string _filePath = AppDomain.CurrentDomain.BaseDirectory + "Exception\\";
                if (_newFile.CheckDirectory(_filePath))
                {
                    string _curMonth = DateTime.Now.Year.ToString("0000") + DateTime.Now.Month.ToString("00");

                    if (!_newFile.CheckDirectory(_filePath + _curMonth))
                    {
                        if (_newFile.CreateDirectory(_filePath, _curMonth))
                        {
                            _filePath += _curMonth + "\\";
                        }
                    }
                    else
                    {
                        _filePath += _curMonth + "\\";
                    }

                    string _fileName = strPrefixFileName + DateTime.Now.ToString("yyyyMMMdd_hhmmss_tt") + ".txt";

                    _newFile.WriteNewFile(_filePath, _fileName, strException);
                    _newFile = null;
                }
            }
            catch (Exception Ex)
            {
                Ex = null;
            }
        }


        private static void CreateMailDeliveryExceptionLog(string strLocation, System.Text.StringBuilder ErrorMessage)
        {
            String[] _fileContent = new String[3];
            _fileContent[0] = "Date Time : " + DateTime.Now.ToString();
            _fileContent[1] = "Location : " + "MyMailManager - " + strLocation;
            _fileContent[2] = "Message : " + ErrorMessage;

            WriteMailDeliveryExceptionLog("MailDelivery_", _fileContent);
        }


        private static void WriteMailDeliveryExceptionLog(string strPrefixFileName, string[] strException)
        {
            try
            {
                FileSystem _newFile = new FileSystem();
                string _filePath = AppDomain.CurrentDomain.BaseDirectory + "Exception\\";
                if (_newFile.CheckDirectory(_filePath))
                {
                    string _curMonth = DateTime.Now.Year.ToString("0000") + DateTime.Now.Month.ToString("00");

                    if (!_newFile.CheckDirectory(_filePath + _curMonth))
                    {
                        if (_newFile.CreateDirectory(_filePath, _curMonth))
                        {
                            _filePath += _curMonth + "\\";
                        }
                    }
                    else
                    {
                        _filePath += _curMonth + "\\";
                    }

                    string _fileName = strPrefixFileName + DateTime.Now.ToString("yyyyMMMdd_hhmmss_tt") + ".txt";

                    _newFile.WriteNewFile(_filePath, _fileName, strException);
                    _newFile = null;
                }
            }
            catch (Exception Ex)
            {
                Ex = null;
            }
        }


    }
}
